package nina.yiyou.attendance.s10merge.compute.latepoint

import groovy.transform.PackageScope
import nina.yiyou.salary.input.config.WorkTimeSheetReader

import static java.util.Comparator.comparing

@PackageScope
class WorkTimeFinder {

  WorkTimeFinder(List<WorkTimeSheetReader.Line> workTimeCfg, String department) {
    _workTimeCfg = workTimeCfg
    _department = department
  }

  WorkTimeSheetReader.Line findTime() {
    def substr = { String s, int len -> len >= s.length() ? s : s.substring(0, len) }

    for (int outLen = _department.size(); outLen > 0; outLen--) {
      String outDept = substr(_department, outLen)

      for (def cfgLine in _workTimeCfg) {
        String deptCfg = cfgLine.department()

        if (deptCfg.length() > outLen) {
          continue
        }
        if (substr(deptCfg, outLen) == outDept) {
          return cfgLine
        }
      }
    }

    return _workTimeCfg.stream()
        .min(comparing { WorkTimeSheetReader.Line l -> l.department().length() })
        .orElse(_workTimeCfg[-1])
  }

  private final List<WorkTimeSheetReader.Line> _workTimeCfg

  private final String _department
}
